import {
  LogoutOutlined,
  SettingOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import type { MenuProps } from 'antd';
import { Spin, Modal, message } from 'antd';
import { createStyles } from 'antd-style';
import React, { useRef } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from '../HeaderDropdown';

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

export const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  return <span className="anticon">{currentUser?.name}</span>;
};

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    logoutModal: {
      position: 'fixed',
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%) !important',
      margin: 0,
      zIndex: 1001,
    },
  };
});

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({
  menu,
  children,
}) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const [modal, contextHolder] = Modal.useModal();
  const modalRef = useRef(modal);

  /**
   * 清除存储的用户信息
   */
  const clearUserStorage = () => {
    try {
      // 清空会话存储中的用户信息
      sessionStorage.clear();
    } catch (error) {
      console.error('清空用户存储信息失败:', error);
    }
  };

  /**
   * 退出登录逻辑
   */
  const loginOut = async () => {
    try {
      // 清空存储的用户信息
      sessionStorage.clear();
      //显示退出成功提示
      message.success('退出登录成功！', 1);
      const { search, pathname } = window.location;
      const urlParams = new URL(window.location.href).searchParams;
      const searchParams = new URLSearchParams({
        redirect: pathname + search,
      });
      const redirect = urlParams.get('redirect');
      // 跳转到登录页
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: searchParams.toString(),
        });
      }

    } catch (error) {
      console.error('退出登录失败:', error);
      message.error('退出登录失败，请重试！', 2);
      setTimeout(() => {
        history.replace('/user/login');
      }, 1000);
    }
  };

  /**
   * 退出确认弹窗
   */
 const showLogoutConfirm = () => {
    modalRef.current.confirm({
      title: '确认退出',
      content: '确定要退出当前登录吗？',
      icon: <LogoutOutlined style={{ color: '#ff4d4f' }} />,
      okText: '确认退出',
      cancelText: '取消',
      okType: 'danger',
      maskClosable: false,
      className: styles.logoutModal,
      // 禁用默认的位置动画
      transitionName: '',
      // 强制指定弹窗容器为 body
      getContainer: () => document.body,
      onOk: async () => {
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: undefined }));
        });
        await loginOut();
      },
      onCancel: () => {
        message.info('已取消退出操作');
        console.log('取消退出');
      },
    });
  };
  const onMenuClick: MenuProps['onClick'] = (event) => {
    const { key } = event;
    if (key === 'logout') {
      showLogoutConfirm();
      return;
    }
    history.push(`/account/${key}`);
  };

  const loading = (
    <span className={styles.action}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return (
      <>
        {loading}
        {contextHolder}
      </>
    );
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.name) {
    return (
      <>
        {loading}
        {contextHolder}
      </>
    );
  }

  const menuItems = [
    ...(menu
      ? [
        {
          key: 'center',
          icon: <UserOutlined />,
          label: '个人中心',
        },
        {
          key: 'settings',
          icon: <SettingOutlined />,
          label: '个人设置',
        },
        {
          type: 'divider' as const,
        },
      ]
      : []),
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  return (
    <>
      <HeaderDropdown
        menu={{
          selectedKeys: [],
          onClick: onMenuClick,
          items: menuItems,
        }}
      >
        {children}
      </HeaderDropdown>
      {contextHolder}
    </>
  );
};